﻿# Create your views here.
# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response,redirect
from django.http import HttpResponse,HttpResponseRedirect
from django.template.loader import get_template
from django.template import Context
from django.db import connection
from datetime import datetime

from show.models import SiteUser

def authenticate(username,password):
        '''
        to authenticate user but also return the user even his or her account has been deactivated
        '''
        users = SiteUser.objects.all().filter(username=username,password=password)
        if users and len(users)>0:
                return users[0]
        else:
                return None
                
                
                
def update_login_info(username, request):
    user=SiteUser.objects.filter(username=username)
    from datetime import datetime
    now = datetime.now()
    user.update(last_login_time=now)
    
def register(request):
    username = request.POST.get('username')
    if not username:
        username = 123
    password = request.POST.get('password')
    if not password:
        password = 123
    phone = request.POST.get('phone')
    if not phone:
        phone = 123
    email = request.POST.get('email')
    if not email:
        email = 123
    line = SiteUser.objects.all().filter(username=username)
    
    if line:
        if username == 123:
            user_mes = " "
        else :
            user_mes = "注册出错，用户名已被注册"
        return render_to_response('register.html',{'user_mes':user_mes})
    else :
        now = datetime.now()
        p = SiteUser(
            username = username,\
            password = password,\
            phone = phone,\
            email = email,\
            isactive = 1,\
            last_login_time = now
        )
        p.save()
        return render_to_response('Login.html')
    
    
def siteuser_login_required(f):
        '''
        decorator to use when resources just need user privilege
        '''
        def wrap(request, *args, **kwargs):
                #this check the session if userid key exist, if not it will redirect to login page
                #secure hole
                if 'username' not in request.session.keys():
                        return render_to_response('Login.html',{'next':request.path})
                return f(request, *args, **kwargs)
        wrap.__doc__=f.__doc__
        wrap.__name__=f.__name__
        return wrap
def siteadmin_login_required(f):
        def wrap(request, *args, **kwargs):
                #this check the session if user id key exist, if not it will redirect to login page
                username=request.session.get('username')
                if username: 
                    admins= SiteUser.objects.all().filter(username=username)
                    if admins and len(admins)>0 :
                      return f(request, *args, **kwargs)
                return render_to_response('Login.html',{'message':'请以管理员身份登录','next':request.path})
        wrap.__doc__=f.__doc__
        wrap.__name__=f.__name__
        return wrap
#TODO
def siteroot_login_required(f):
        '''
        decorator to use when resources need administrator privilege
        '''
        def wrap(request, *args, **kwargs):
                #this check the session if user id key exist, if not it will redirect to login page
                username=request.session.get('username','')
                if username=='root': 
                    admins= SiteUser.objects.all().filter(username=username,isadmin=True)
                    if admins and len(admins)>0 :
                      return f(request, *args, **kwargs)
                return render_to_response('Login.html',{'message':'请以root身份登录','next':request.path})
        wrap.__doc__=f.__doc__
        wrap.__name__=f.__name__
        return wrap
        
def login(request):
        '''
        
        '''
        if request.method == 'GET':
            return render_to_response('Login.html',{})
        elif request.method == 'POST':
            username = request.POST.get('username')
            password = request.POST.get('password')
            next=request.POST.get('next')#page return "" on empty,so check it afterward
            remember=request.POST.get('remember')
            if not next:
                next='/'
            user = authenticate(username=username, password=password)
            if user and user.isactive:
                if remember and remember =="on":
                    request.session.set_expiry(21600)#6*3600 expire in 6 hours
                else:
                    request.session.set_expiry(1200)#expire in 5 minutes
                request.session['username'] = username
                login_info = {'last_login_time':user.last_login_time}
                request.session['logininfo'] = login_info
                update_login_info(username, request)
                return redirect(next)
            elif user and user.isactive==False:
                message="账户 %s 已被冻结,请联系管理员" % user.username
                return render_to_response('Login.html',{'message':message,'next':next})
            else:
                message="用户名或密码错误，请重试"
                print message,'message'
                return render_to_response('Login.html',{'message':message,'next':next})


  
  
def logout(request):
        request.session.clear()
        next=request.path
        #FIXME this do nothing because request.path == '/logout/' always return true
        if request.path =='/logout/':#this avoid jumps between login and logout
           next='/'
        return render_to_response('Login.html',{'message':'你已经注销，请重新登录','next':next})

